import axios from "axios";
import { session } from "@/service/storage.service";
const { VITE_STORAGE_TOKEN } = import.meta.env;

// axios 请求方式枚举
enum METHOD {
  GET = "GET",
  DELETE = "DELETE",
  HEAD = "HEAD",
  OPTIONS = "OPTIONS",
  POST = "POST",
  PUT = "PUT",
  PATCH = "PATCH",
  PURGE = "PURGE",
  LINK = "LINK",
  UNLINK = "UNLINK",
}
export { METHOD };

enum STATUS {
  SUCCESS = "ok",
  FAIL = "fail",
}

/**
 * 构建axios实例并增加拦截器
 * @author WangLiZhi
 * @param baseURL
 * @param config
 * @returns 
 */
function create(baseURL = "", config = {}) {
  // 初始化axios实例
  const http = axios.create({
    timeout: 30000, // 设置超时
    baseURL: baseURL, // 设置统一接口地址
    headers: {
      "Content-Type": "application/json;charset=UTF-8;", // 设置内容数据格式和编码
    },
    ...config,
  });

  /**
   * 请求拦截器
   * 1.添加token到header上
   */
  http.interceptors.request.use(
    (config) => {
      // http header上添加token
      const token = session.get(VITE_STORAGE_TOKEN);
      token && (config.headers.Authorization = token);
      return config;
    },
    (error) => Promise.reject(error)
  );

  // 响应拦截白名单
  const whiteList = [200, 201];
  /**
   * 响应拦截器
   * 1.响应数据格式化
   * 2.请求错误处理
   */
  http.interceptors.response.use(
    (response) => {
      if (whiteList.includes(response.status)) {
        return Promise.resolve(response);
      }
      return Promise.reject(response);
    },
    (error) => {
      const code = error?.response?.status;
      if (code) {
        let message;
        switch (code) {
          case 400:
            message = "请求错误!";
            break;
          case 401:
            message = "请求错误!";
            break;
          case 404:
            message = "此刻无数据!";
            break;
          case 408:
            message = "请求超时!";
            break;
          case 500:
            message = "服务器内部错误!";
            break;
          case 501:
            message = "服务未实现!";
            break;
          case 502:
            message = "网关错误!";
            break;
          case 503:
            message = "服务不可用!";
            break;
          case 504:
            message = "网关超时!";
            break;
          case 505:
            message = "HTTP版本不受支持!";
            break;
          default:
            message = "请求失败!";
        }
      }
      return Promise.reject(error);
    }
  );
  return http;
}

// 创建请求接口的axios实例
export const request = create(import.meta.env.VITE_API_URL as string);
